﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using common4gp;
using System.Diagnostics.Contracts;

namespace wpf4gp.Dependencies
{
    /// <summary>
    /// <see cref="System.Windows.DependencyProperty"/> for DialogResult property
    /// </summary>
    public static class DialogCloser
    {

        /// <summary>
        /// <see cref="System.Windows.DepenencyProperty"/> to attach
        /// </summary>
        private static readonly DependencyProperty _dialogResultProperty =
            DependencyProperty.RegisterAttached(
                "DialogResult",
                typeof(bool?),
                typeof(DialogCloser),
                new PropertyMetadata(DialogResultChanged));


        /// <summary>
        /// <see cref="System.Windows.DepenencyProperty"/> to attach
        /// </summary>
        public static DependencyProperty DialogResultProperty
        {
            get
            {
                return _dialogResultProperty;
            }
        }


        /// <summary>
        /// Changed the value of the DialogResult property
        /// </summary>
        /// <param name="d">Dependency object</param>
        /// <param name="e">Event args</param>
        private static void DialogResultChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var window = d as Window;
            if (window.IsNotNull())
            {
                window.DialogResult = e.NewValue as bool?;
            }
        }

        /// <summary>
        /// Set the DialogResult property to a specific value
        /// </summary>
        /// <param name="target">Window to set the property</param>
        /// <param name="value">Value to set</param>
        public static void SetDialogResult(Window target, bool? value)
        {
            Contract.Requires<ArgumentNullException>(target.IsNotNull());
            target.SetValue(DialogResultProperty, value);
        }
    }
}
